1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package com.google.common.collect;
16
17 import com.google.caliper.BeforeExperiment;
18 import com.google.caliper.Benchmark;
19 import com.google.caliper.Param;
20
21 import java.util.Arrays;
22 import java.util.Comparator;
23 import java.util.Random;
24
25
26
27
28
29
30
31
32 public class ComparatorDelegationOverheadBenchmark {
33 private final Integer[][] inputArrays = new Integer[0x100][];
34
35 @Param({"10000"})
36 int n;
37
38 @BeforeExperiment
39 void setUp() throws Exception {
40 Random rng = new Random();
41 for (int i = 0; i < 0x100; i++) {
42 Integer[] array = new Integer[n];
43 for (int j = 0; j < n; j++) {
44 array[j] = rng.nextInt();
45 }
46 inputArrays[i] = array;
47 }
48 }
49
50 @Benchmark int arraysSortNoComparator(int reps) {
51 int tmp = 0;
52 for (int i = 0; i < reps; i++) {
53 Integer[] copy = inputArrays[i & 0xFF].clone();
54 Arrays.sort(copy);
55 tmp += copy[0];
56 }
57 return tmp;
58 }
59
60 @Benchmark int arraysSortOrderingNatural(int reps) {
61 int tmp = 0;
62 for (int i = 0; i < reps; i++) {
63 Integer[] copy = inputArrays[i & 0xFF].clone();
64 Arrays.sort(copy, Ordering.natural());
65 tmp += copy[0];
66 }
67 return tmp;
68 }
69
70 private static final Comparator<Integer> NATURAL_INTEGER = new Comparator<Integer>() {
71 @Override
72 public int compare(Integer o1, Integer o2) {
73 return o1.compareTo(o2);
74 }
75 };
76
77 @Benchmark int arraysSortOrderingFromNatural(int reps) {
78 int tmp = 0;
79 for (int i = 0; i < reps; i++) {
80 Integer[] copy = inputArrays[i & 0xFF].clone();
81 Arrays.sort(copy, Ordering.from(NATURAL_INTEGER));
82 tmp += copy[0];
83 }
84 return tmp;
85 }
86 }